import { defineStore } from 'pinia'
import { login } from '../api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    accessToken: localStorage.getItem('accessToken') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  }),

  actions: {
    async loginAction(username, password) {
      try {
        const res = await login({ username, password })
        if (res.success) {
          const { data } = res
          this.accessToken = data.accessToken
          this.refreshToken = data.refreshToken
          this.userInfo = {
            adminId: data.adminId,
            name: data.name,
            avatar: data.avatar
          }

          // 存储到localStorage
          localStorage.setItem('accessToken', data.accessToken)
          localStorage.setItem('refreshToken', data.refreshToken)
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

          ElMessage.success('登录成功')
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败：', error)
        ElMessage.error(error.message || '登录失败')
        return false
      }
    },

    logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.userInfo = {}

      // 清除localStorage
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    }
  },

  getters: {
    isLoggedIn: (state) => !!state.accessToken,
    getUserInfo: (state) => state.userInfo,
  }
})
